package cc.customer.aiEmport.services.Impl;

import cc.customer.aiEmport.damain.CAiEmp;
import cc.customer.aiEmport.dao.CaiEmpMapper;
import cc.customer.aiEmport.services.AiEmpServices;
import cc.customer.bigEmport.damain.EpRecords;
import cc.customer.bigEmport.damain.EprRecords;
import cc.customer.bigEmport.damain.IpRecords;
import cc.customer.bigEmport.dao.EpRecordsMapper;
import cc.customer.bigEmport.dao.EprRecordsMapper;
import cc.customer.bigEmport.dao.IpRecordsMapper;
import cc.customer.common.domain.QueryRequest;
import cc.customer.common.domain.ResponseBo;
import cc.customer.common.service.impl.BaseService;
import cc.customer.common.utils.Constant;
import cc.customer.common.utils.FebsUtil;
import cc.customer.common.utils.Utils;
import cc.customer.cusDynamic.domain.CusDynamic;
import cc.customer.cusDynamic.services.CusDynamicService;
import cc.customer.system.dao.UserMapper;
import cc.customer.system.domain.MyUser;
import cc.customer.utils.AutonCusInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Description: customer
 * Created by yhsh on 2020/3/24 10:00
 * version 2.0
 * 方法说明
 */
@Service
public class AiEmpServicesImpl extends BaseService<CAiEmp> implements AiEmpServices {

	private static final Logger logger = LoggerFactory.getLogger(AiEmpServicesImpl.class);


	@Autowired
	private EpRecordsMapper epRecordsMapper;
	@Autowired
	private EprRecordsMapper eprRecordsMapper;

	@Autowired
	private CaiEmpMapper caiEmpMapper;

	@Autowired
	private IpRecordsMapper ipRecordsMapper;

	@Autowired
	private CusDynamicService cusDynamicService;

	@Autowired
	private UserMapper userMapper;

	@Override
	public List<CAiEmp> getAllAiEmpServices(CAiEmp aiEmp, QueryRequest request, String isBig, MyUser user) {
		try {
			Example example = new Example(CAiEmp.class);
			Example.Criteria criteria = example.createCriteria();
			/**查询批次**/
			String batch = aiEmp.getAiBatch();
			if(!StringUtils.isEmpty(batch)){
				criteria.andLike("aiBatch","%"+batch+"%");
			}
			/**查询专员**/
			String bpDirector = aiEmp.getAiDirector();
			if (!StringUtils.isEmpty(bpDirector)){
				criteria.andLike("aiDirector","%"+bpDirector+"%");
			}

			/**意向等级**/
			String bpGroud = aiEmp.getAiGroud();
			if (!StringUtils.isEmpty(bpGroud)){
				try {
					List<String> list = Arrays.asList(bpGroud.split(","));
					criteria.andIn("aiGroud",list);
				}catch (Exception e){
					logger.error("查询Ai资源客户的 意向等级 失败："+e.getMessage());
				}
			}

			/**资源类型**/
			String bpResType = aiEmp.getAiResType();
			if(!StringUtils.isEmpty(bpResType)){
				criteria.andCondition("ai_res_type = ",bpResType);
			}else{
				List<String> list = new ArrayList<>(Arrays.asList(Constant.BIGEMP_RESOURCE_TYPE));
				criteria.andIn("aiResType",list);
			}

			/**客户新增时间**/
			String starttime=  aiEmp.getStarttime();
			String endtime = aiEmp.getEndtime();
			if (!StringUtils.isAnyEmpty(starttime,endtime)){
				criteria.andBetween("aiCreatetime",starttime,endtime+" 23:59:59");
			}else if (!StringUtils.isEmpty(starttime)){
				criteria.andCondition("aiCreatetime = ",starttime);
			}
			/**客户的状态**/
			/*if (!StringUtils.isEmpty(isBig)){
				//未分配
				criteria.andIsNull("aiDistriute");
			}*/

			/**地区**/
			if(!StringUtils.isEmpty(aiEmp.getAiZone())){
				criteria.andEqualTo("aiZone",aiEmp.getAiZone());
			}

			if(!StringUtils.isEmpty(isBig)){
				//已分配
				if("1".equals(isBig)){
					criteria.andIsNotNull("aiDistriute");
				}else if("2".equals(isBig)){
					//未分配
					criteria.andIsNull("aiDistriute");
				}
			}
			/**筛选部门*/
			if(!StringUtils.isEmpty(aiEmp.getAiDeptid())){
				List<MyUser> userList = userMapper.findUserByDepid(aiEmp.getAiDeptid());
				List<String> list = new ArrayList<>();
				for(MyUser user1:userList){
					list.add(user1.getUserUuid());
				}
				criteria.andIn("aiDistriute",list);
			}

			/**筛选跟进人*/
			if(!StringUtils.isEmpty(aiEmp.getAiDistriute())){
				criteria.andEqualTo("aiDistriute",aiEmp.getAiDistriute());
			}
			criteria.andEqualTo("aiIsdelete","0");
			/**加入查询条件**/
			//排序条件
			example.setOrderByClause(" ai_createtime desc ");
			List<CAiEmp> aiEmpsEmpList = this.selectByExample(example);

			List<MyUser> uslist = userMapper.selectAllUser();
			for (CAiEmp aiEmp1:aiEmpsEmpList){
				AutonCusInfo.parseCAiEmp(aiEmp1,user);

				for(MyUser user1:uslist){
					if(aiEmp1!=null&&!StringUtils.isEmpty(aiEmp1.getAiDistriute())){
						if(aiEmp1.getAiDistriute().equals(user1.getUserUuid())){
							aiEmp1.setAiDistriute(user1.getNickname());
							aiEmp1.setAiDeptName(user1.getDeptName());
						}
					}
				}
			}
			return aiEmpsEmpList;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取ai资源失败:"+e.getMessage());
			return new ArrayList<>();
		}
	}

	@Override
	public ResponseBo deleteAiEmpResource(String deletsids){
		try {
			String idsArray [] = deletsids.split(",");
			List<String> list = new ArrayList<>();
			for (String id:idsArray){ list.add(id); }
			CAiEmp bigEmp = new CAiEmp();
			bigEmp.setAiIsdelete("1");
			int num  = this.batchUpdate(list,"aiId",CAiEmp.class,bigEmp);
			if (num<=0){
				return ResponseBo.error("删除客户得信息失败");
			}
		}catch (Exception e){
			logger.error("删除AI资源失败："+e.getMessage());
			return ResponseBo.error("删除失败");
		}
		return ResponseBo.ok("删除成功");
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW ,rollbackFor = Exception.class)
	public int batchInsert(List<CAiEmp> list, List<EprRecords> Chongfu,EpRecords records) throws Exception{

		List<CAiEmp> all = new ArrayList<>();
		List<EprRecords> allChongfu = new ArrayList<>();
		int num = 0;
		for (CAiEmp big:list){
			//验证 手机号 是不是已经存在了
			all.add(big);
			if(all.size()>1000){
				int num1 = caiEmpMapper.insertList(all);
				num +=num1;
				all.clear();
			}
		}
		//最后插入结束
		int numlast = 0;
		if(!all.isEmpty()){
			numlast = caiEmpMapper.insertList(all);
		}
		/**重复数据* **/
		//验证数据库有的数据 执行插入到其他的表里面
		if (!Chongfu.isEmpty()){
			for (EprRecords big:Chongfu){
				//分批插入
				allChongfu.add(big);
				if(allChongfu.size()>2000){
					eprRecordsMapper.insertList(allChongfu);
					allChongfu.clear();
				}
			}
			if (!allChongfu.isEmpty()){
				eprRecordsMapper.insertList(allChongfu);
			}
		}
		num+=numlast;
		//批量插入完成 后执行批量插入的 记录
		epRecordsMapper.insert(records);
		return num;
	}
	@Override
	public void exportBigEmpRecords(String exportids, String user, String exportMsg) throws Exception {
		try {
			IpRecords ipRecords = new IpRecords();
			ipRecords.setcIpIds(exportids);
			/**导出的数量**/
			String []exportsIds  = exportids.split(",");
			ipRecords.setcIpNum(exportsIds.length);
			List<String> idsall = new ArrayList<>();
			for(String id:exportsIds){
				idsall.add(id);
			}

			/**导出AI资源名单的 批次**/
			String exportname = Utils.getExportBatchName(idsall.size()+"");
			ipRecords.setcIpIname(exportname);
			String uuid = Utils.getUUID();
			ipRecords.setcIpUuid(uuid);
			ipRecords.setcIpTime(new Date());
			ipRecords.setcIpOption(user);
			ipRecords.setcIpStatus("0");
			ipRecords.setcIpIsover("0");
			ipRecords.setcIpType(Constant.ZIYUAN_TYPE_EXEMP);
			ipRecords.setcIpUserfo(exportMsg);
			ipRecords.setcIpIcomdtion("");
			ipRecordsMapper.insert(ipRecords);

		}catch (Exception e){
			e.printStackTrace();
			logger.error("导出记录失败");
			throw  new RuntimeException("");
		}
	}

	@Override
	public List<String> getAllAIData() {

		List<String> listNum = new ArrayList<>();
		try {
			Example example = new Example(CAiEmp.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("aiIsdelete","0");
			List<CAiEmp> list = this.selectByExample(example);
			for (CAiEmp emp :list){
				listNum.add(emp.getAiMobile());
			}
		}catch (Exception e){
			logger.error("查询所有的失败"+e.getMessage());
		}
		return listNum;
	}

	@Override
	public List<CAiEmp> getallcAidByEmpUuid(String uuid, String condation) {
		try {
			Example example = new Example(CAiEmp.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andCondition("ai_uuid=",uuid).andEqualTo("aiIsdelete","0");
			Example.Criteria criteria1 = example.createCriteria();
			if (!StringUtils.isEmpty(condation)){
				criteria1.orLike("aiName","%"+condation+"%").orLike("aiMobile","%"+condation+"%");
			}
			example.and(criteria1);
			List<CAiEmp> list = this.selectByExample(example);
			return list;
		}catch (Exception e){
			logger.error("获取当前批次的Ai资源失败:"+e.getMessage());
		}
		return new ArrayList<>();
	}

	@Override
	public List<CAiEmp> getAllAiByempAllUuid(String exportids, MyUser user) {
		String []exportsIds  = exportids.split(",");
		List<String> ids = new ArrayList<>();
		for(String id:exportsIds){
			ids.add(id);
		}
		Example example = new Example(CAiEmp.class);
		example.createCriteria().andIn("aiId",ids);
		List<CAiEmp> emps =  this.selectByExample(example);
		emps.forEach( emp ->{ AutonCusInfo.parseCAiEmp(emp,user); });
		return emps;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
	public ResponseBo executeAIDisfenpei(CAiEmp caiEmp, String ids, String userid) {
		try {
			List<String> list = Arrays.asList(ids.split(","));
			int num  = this.batchUpdate(list,"aiId",CAiEmp.class,caiEmp);
			if (num > 0){
				/**增加操作记录**/
				cusDynamicService.batchInsertAiEmpDisture(list,caiEmp);
				return ResponseBo.ok("更新客户的信息成功");
			}
		}catch (Exception e){
			e.printStackTrace();
			logger.error("更新客户失败:"+e.getMessage());
			throw  new RuntimeException();
		}
		return ResponseBo.error("更新客户的信息失败");
	}
	@Override
	public ResponseBo findAllAiEmpInfoById(String keyid,MyUser user) {
		try {
			CAiEmp igEmpbig = caiEmpMapper.selectCustomerDetail(keyid);
			CAiEmp emp = AutonCusInfo.parseCAiEmp(igEmpbig,user);
			return  ResponseBo.ok(emp);
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取客户资料失败 :"+e.getMessage());
		}
		return ResponseBo.error("获取客户资料失败");
	}

	@Override
	public ResponseBo appFindAllAiEmpInfoById(String keyid,MyUser user) {
		try {
			CAiEmp igEmpbig = caiEmpMapper.selectCustomerDetail(keyid);
			return  ResponseBo.ok(igEmpbig);
		}catch (Exception e){
			logger.error("获取客户资料失败 :"+e.getMessage());
		}
		return ResponseBo.error("获取客户资料失败");
	}

	@Override
	public ResponseBo changeAiEmpInfo(CAiEmp caiEmp, MyUser user) {
		try {
			/**如果更新得是手机号，则验证手机号 是不是存在 如果存在 则不能更新**/
			String mobilePhone = caiEmp.getAiMobile();
			if (!StringUtils.isEmpty(mobilePhone)){
				//验证手机号
				if (!FebsUtil.isPhoneNo(mobilePhone)){
					return ResponseBo.error("当前手机号不正确，不允许更新");
				}
				CAiEmp isHave = findAiEmpByMobile(mobilePhone);
				if (isHave !=null){
					if(!isHave.getAiId().equals(caiEmp.getAiId())){
						return ResponseBo.error("当前手机号已经存在，不允许更新");
					}
				}
			}
			int num = this.updateNotNull(caiEmp);
			if (num <= 0){
				return ResponseBo.error("修改失败,修改条目:"+num);
			}
		}catch (Exception e){
			logger.error("修改客户得信息失败:"+e.getMessage());
			return ResponseBo.error("修改客户得信息失败:"+e.getMessage());
		}
		if (!StringUtils.isEmpty(caiEmp.getAiStage())){
			List<String> list = new ArrayList<>();
			list.add(caiEmp.getAiId()+"");
			CusDynamic cus = new CusDynamic();
			cus.setDyCreator(user.getUserUuid());
			cus.setDyType(Constant.CUSTOMER_RECORD_STATAGES);
			cus.setDySourceType("5");
			String stta = AutonCusInfo.parseCustomerStage(caiEmp.getAiStage());
			cus.setDyContent(user.getNickname()+" 更改了客户阶段: "+stta);
			cusDynamicService.inserDynamic(list,cus);
		}
		return ResponseBo.ok("修改客户资料成功");
	}
	@Override
	public CAiEmp findAiEmpByMobile(String Mobile) {
		Example example = new Example(CAiEmp.class);
		example.createCriteria().andCondition("ai_mobile=",Mobile).andEqualTo("aiIsdelete","0");
		List<CAiEmp> list = this.selectByExample(example);
		return list.isEmpty() ? null : list.get(0);
	}
	@Override
	public ResponseBo selectAiEmpLabel(String keyid) {
		try {
			CAiEmp igEmpbig = caiEmpMapper.selectAiEmpLabel(keyid);
			return  ResponseBo.ok(igEmpbig);
		}catch (Exception e){
			logger.error("获取客户资料失败 :"+e.getMessage());
		}
		return ResponseBo.error("获取客户资料失败");
	}


}
